#pragma once
#include <cstdlib>
#include <iostream>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/CommonRequest.h>
#include <alibabacloud/core/CommonClient.h>
#include <alibabacloud/core/CommonResponse.h>

#include "logger.hpp"


namespace im{
    /*
    *  阿里云短信服务api技术文档：https://next.api.aliyun.com/api/Dysmsapi/2017-05-25/SendSms?params={%22SignName%22:%22IM%E5%8D%B3%E6%97%B6%E9%80%9A%E8%AE%AF%E7%B3%BB%E7%BB%9F%22,%22TemplateCode%22:%22SMS_479830019%22,%22PhoneNumbers%22:%2218370804132%22,%22TemplateParam%22:%22%7B%5C%22code%5C%22%3A%5C%221234%5C%22%7D%22}&sdkStyle=old&RegionId=cn-chengdu&tab=DOC&lang=CPP
    */
    class DMSClient{
    public:
        using ptr = std::shared_ptr<DMSClient>;
        DMSClient(const std::string& access_key_id, const std::string& access_secret){
            AlibabaCloud::InitializeSdk();
            AlibabaCloud::ClientConfiguration configuration( "cn-shenzhen" );
            // specify timeout when create client.
            configuration.setConnectTimeout(1500);
            configuration.setReadTimeout(4000);
            AlibabaCloud::Credentials credential(access_key_id, access_secret);
            _client = std::make_unique<AlibabaCloud::CommonClient>(credential, configuration);
        }

        ~DMSClient(){
            AlibabaCloud::ShutdownSdk();
        }

        bool send_verify_code(const std::string& phone, const std::string& verify_code){
            AlibabaCloud::CommonRequest request(AlibabaCloud::CommonRequest::RequestPattern::RpcPattern);
            request.setHttpMethod(AlibabaCloud::HttpRequest::Method::Post);
            request.setDomain("dysmsapi.ap-southeast-1.aliyuncs.com");
            request.setVersion("2017-05-25");
            request.setQueryParameter("Action", "SendSms");
            request.setQueryParameter("SignName", "IM即时通讯系统");
            request.setQueryParameter("TemplateCode", "SMS_479830019");
            request.setQueryParameter("PhoneNumbers", phone);
            std::string code = "{\"code\":\"" + verify_code + "\"}";
            request.setQueryParameter("TemplateParam", code);

            auto response = _client->commonResponse(request);
            if (response.isSuccess()) {
                LOG_INFO("request success.");
                LOG_INFO("result: {}", response.result().payload());
                return true;
            } else {
                LOG_CRITICAL("短信验证码请求失败：{}", response.error().errorMessage());
                LOG_CRITICAL("request id: {}", response.error().requestId());
                return false;
            }
        }

    private:
        std::unique_ptr<AlibabaCloud::CommonClient> _client;
    };
}